﻿using System;
using PTop.Code;
using PTop.Domain.Entity.SystemManage;
using PTop.Domain.IRepository.SystemManage;
using PTop.Domain.ViewModel.SystemManage;
using PTop.Repository.SystemManage;
using System.Collections.Generic;
using System.Linq;

namespace PTop.Application.SystemManage
{
    public class ItemsDetailApp
    {
        private IItemsDetailRepository service = new ItemsDetailRepository();

        public List<ItemsDetailEntity> GetList(string itemId = "", string keyword = "")
        {
            var expression = ExtLinq.True<ItemsDetailEntity>();
            if (!string.IsNullOrEmpty(itemId))
            {
                expression = expression.And(t => t.F_ItemId == itemId);
            }
            if (!string.IsNullOrEmpty(keyword))
            {
                expression = expression.And(t => t.F_ItemName.Contains(keyword));
                expression = expression.Or(t => t.F_ItemCode.Contains(keyword));
            }
            return service.IQueryable(expression).OrderBy(t => t.F_SortCode).ToList();
        }
        public List<ItemsDetailEntity> GetItemList(string enCode)
        {
            return service.GetItemList(enCode);
        }
        public ItemsDetailEntity GetForm(string keyValue)
        {
            return service.FindEntity(keyValue);
        }
        public void DeleteForm(string keyValue)
        {
            service.Delete(t => t.F_Id == keyValue);
        }
        public void SubmitForm(ItemsDetailEntity itemsDetailEntity, string keyValue)
        {
            if (!string.IsNullOrEmpty(keyValue))
            {
                itemsDetailEntity.Modify(keyValue);
                service.Update(itemsDetailEntity);
            }
            else
            {
                itemsDetailEntity.Create();
                service.Insert(itemsDetailEntity);
            }
        }

        #region For Front

        private static readonly object Lock = 1;

        public List<ItemsDetailModel> GetItemListCached(string enCode)
        {
            string cacheKey = "ItemList_" + enCode;
            var list = CacheFactory.Cache().GetCache<List<ItemsDetailModel>>(cacheKey);
            if (list == null)
            {
                lock (Lock)
                {
                    list = CacheFactory.Cache().GetCache<List<ItemsDetailModel>>(cacheKey);
                    if (list == null)
                    {
                        var itemList = service.GetItemList(enCode);
                        list = itemList.Select(item => new ItemsDetailModel
                        {
                            ItemCode = item.F_ItemCode,
                            ItemName = item.F_ItemName
                        }).ToList();
                        CacheFactory.Cache().WriteCache(list, cacheKey, DateTime.Now.AddHours(1));
                    }
                }
            }
            return list;
        }

        #endregion
    }
}
